﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using blacksoftFINAL.Models;
using System.Security.Cryptography;
using System.Text;


namespace blacksoftFINAL.Controllers
{
    public class LoginEmpleadoController : Controller
    {
        private inf245travelbusEntities1 db = new inf245travelbusEntities1();
        public ActionResult Index()
        {
            return View();
        }
        [HttpPost]
        public ActionResult Index([Bind(Include = "Nombre,Contraceña,IDPersona,IDPerfil")] Usuario user)
        {
            var query = from p in db.Usuario
                        where p.Nombre.Equals(user.Nombre)
                        select new
                        {
                            p.Nombre,
                            p.Contraseña
                        };
            if (query.Any())
                {
                    using (MD5 md5Hash = MD5.Create())
                       {
                            string hash = GetMd5Hash(md5Hash, user.Contraseña);
                            if (query.First().Contraseña.Equals(hash))
                            {
                                Session["LoginUsuario"] = user.Nombre;
                                    {//PERMISOS 
                                    
                                
                                    }
                                return RedirectToAction("index", "Home");//ME LOGUIE
                            }
                            TempData["alertMessage"] = "La Contraceña es Incorrecta";
                            return View();//CONTRACEÑA ERRADA
                       }
                }
            else 
                {
                    TempData["alertMessage"] = "El Nombre no Registrado";
                    return View();//USUARIO NO EXISTE
                }
            
        }


        static string GetMd5Hash(MD5 md5Hash, string input)
        {

            // Convert the input string to a byte array and compute the hash.
            byte[] data = md5Hash.ComputeHash(Encoding.UTF8.GetBytes(input));

            // Create a new Stringbuilder to collect the bytes
            // and create a string.
            StringBuilder sBuilder = new StringBuilder();

            // Loop through each byte of the hashed data 
            // and format each one as a hexadecimal string.
            for (int i = 0; i < data.Length; i++)
            {
                sBuilder.Append(data[i].ToString("x2"));
            }

            // Return the hexadecimal string.
            return sBuilder.ToString();
        }



	}
}